package com.huangjue.backend.controller;

import com.huangjue.backend.constant.PromptWords;
import com.huangjue.backend.constant.ResponseFormats;
import com.huangjue.backend.dto.ConversationRequest;
import com.huangjue.backend.entity.Homework;
import com.huangjue.backend.mapper.HomeworkMapper;
import com.huangjue.backend.mapper.AiProgrammingConversationMapper;
import com.huangjue.backend.prompt.BuildPrompt;
import com.huangjue.backend.prompt.impl.BuildPromptImpl;
import com.huangjue.backend.service.AiConversationService;
import com.huangjue.backend.service.AiService;
import com.huangjue.backend.utils.PromptBuilderUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;

@RestController
@RequestMapping("/api/ai")
@CrossOrigin(origins = "*") // 允许跨域请求
public class AiController {

    @Autowired
    private  AiService AiService;
    @Autowired
    private AiConversationService Ai;
    @Autowired
    private HomeworkMapper homeworkMapper;
    @Autowired
    private AiProgrammingConversationMapper aiProgrammingConversationMapper;

    //实现对代码片段进行评分
    /*请求体示例
     *多文件可以通过阅读文件内容将几个文件里的代码读出来并且组合后输出
     * 请求地址示例：http://localhost:8080/api/ai/assignmentScore?userId=123&assignmentId=5（需确保assignmentId在表assignments_demand的记录中存在）
     * 请求体：
         {
            "code": "public class Main {\n    public static void main(String[] args) {\n        System.out.println(\"Hello\");\n    }\n}",
          }
          * 输出为全部文字内容生成后一起输出
          * 使用的大模型为deepseek
     */
    @PostMapping("/assignmentScore")
    public ResponseEntity<?> assignmentScore(@RequestBody String code,
                                             @RequestParam Integer userId,
                                             @RequestParam Integer assignmentId) {

        Map<String, Object> serviceResponse = AiService.assignmentScore(code, userId, assignmentId);

        // 统一响应处理
        return ResponseEntity.status((Integer) serviceResponse.getOrDefault("code", 500))
                .body(Map.of(
                        "code", serviceResponse.get("code"),
                        "message", serviceResponse.get("message"),
                        "data", serviceResponse.get("data")
                ));
    }




    /**
     * 流式代码审阅接口
     * 对单个代码片段进行代码审阅，输出为流式输出
     */
    @PostMapping(value = "/streamReview")
    public Flux<String> streamReview(@RequestBody String code,
                                     @RequestParam Integer userId,
                                     @RequestParam String homeworkId) {
        String relativePath = null;
        final java.util.concurrent.atomic.AtomicInteger conversationId = new java.util.concurrent.atomic.AtomicInteger(-1);
        try {
            String relativeDir = "uploads/homework/" + userId + "/";
            String absDir = System.getProperty("user.dir") + "/" + relativeDir;
            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm-ss");
            String timestamp = now.format(formatter);

            String fileName = homeworkId + "_" + timestamp + ".txt";
            String absPath = absDir + fileName;
            java.io.File dir = new java.io.File(absDir);
            if (!dir.exists()) dir.mkdirs();
            java.nio.file.Files.write(java.nio.file.Paths.get(absPath), code.getBytes(java.nio.charset.StandardCharsets.UTF_8));
            relativePath = relativeDir + fileName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 插入AiProgrammingConversation表
        if (relativePath != null) {
            Integer maxRound = null;
            try {
                maxRound = aiProgrammingConversationMapper.selectMaxRoundNumber(userId.toString(), homeworkId);
            } catch (Exception e) {}
            int roundNumber = (maxRound == null) ? 1 : maxRound + 1;
            com.huangjue.backend.entity.AiProgrammingConversation conv = new com.huangjue.backend.entity.AiProgrammingConversation();
            conv.setUserId(userId.toString());
            conv.setHomeworkId(homeworkId);
            conv.setUserMessage("1\n[文件链接]：" + relativePath);
            conv.setAiResponse("");
            conv.setRoundNumber(roundNumber);
            aiProgrammingConversationMapper.insertConversation(conv);
            conversationId.set(conv.getConversationId());
        }
        Homework homework = homeworkMapper.selectById(Integer.valueOf(homeworkId));

        StringBuilder aiResult = new StringBuilder();

        BuildPrompt promptBuilder = new BuildPromptImpl()
                .role(PromptWords.defaultRole)
                .action(PromptWords.defaultAction)
                .example(PromptWords.defaultExample)
                .format(PromptWords.defaultFormat)
                .constrains(PromptWords.defaultConstrains);

        String systemPrompt = promptBuilder.buildSystemPrompt();

        String userPrompt = PromptBuilderUtil.buildDefaultSystemPrompt(homework.getDescription(),code);



        // 调用大模型
            return AiService.callStream(systemPrompt,userPrompt,0, ResponseFormats.TEXT,null)
                    .doOnCancel(() -> {
                        //todo- 检测到前端断开时触发,异常处理
                        System.out.println("客户端断开，取消大模型请求");
                    })
                    .doOnNext(aiResult::append)
                    .doOnComplete(() -> {
                        if (conversationId.get() != -1) {
                            com.huangjue.backend.entity.AiProgrammingConversation updateConv = new com.huangjue.backend.entity.AiProgrammingConversation();
                            updateConv.setConversationId(conversationId.get());
                            updateConv.setAiResponse(aiResult.toString());
                            System.out.println(aiResult.toString());
                            aiProgrammingConversationMapper.updateConversation(updateConv);

                            //为智能体进行数据存储
                            AiService.homework_summary(code,userId, Integer.parseInt(homeworkId));
                        }
                    });

    }

    @PostMapping("/conversation")
    public Flux<String> test(@RequestBody ConversationRequest Request){

        return Ai.Conversation(Request)
                .doOnCancel(() -> {
                    // 检测到前端断开时触发
                    System.out.println("客户端断开，取消大模型请求");
                });
    }

    @PostMapping("/checkHomework")
    public Map<String, Object> checkHomework(@RequestBody String code,
                                @RequestParam Integer userId,
                                @RequestParam Integer homeworkId){
        return AiService.checkHomework(code, userId, homeworkId);

    }
}
